<?php

namespace app\modules\agent\controllers;

use app\models\AgentLog;
use app\models\AgentPublish;
use Yii;
use yii\base\Exception;
use yii\helpers\FileHelper;
use yii\helpers\Inflector;
use yii\helpers\Url;
use yii\web\NotFoundHttpException;
use yii\web\UploadedFile;

/**
 * 宣传管理
 * Class PublishController
 * @package app\modules\agent\controllers
 */
class PublishController extends BaseController
{
    /**
     * 信息列表
     * @return string
     */
    public function actionList()
    {
        $query = AgentPublish::find();
        $query->andWhere(['agent_id' => $this->agent->id]);
        $query->orderBy('sort DESC');
        $publishList = $query->all();
        return $this->render('list', [
            'publishList' => $publishList,
        ]);
    }

    /**
     * 添加修改信息
     * @return string
     * @throws NotFoundHttpException
     * @throws \yii\base\Exception
     */
    public function actionEdit()
    {
        $id = $this->get('id');
        if (!empty($id)) {
            $publish = AgentPublish::findOne(['id' => $id]);
            if (empty($publish) || $publish->agent_id != $this->agent->id) {
                throw new NotFoundHttpException('没有找到信息。');
            }
        } else {
            $publish = new AgentPublish();
            $publish->agent_id = $this->agent->id;
        }
        if ($publish->load($this->post())) {
            if (in_array($publish->type, [AgentPublish::TYPE_FILE, AgentPublish::TYPE_IMAGE])) {
                $file = UploadedFile::getInstance($publish, 'value');
                if (!empty($file)) {
                    $relative_path = 'publish/' . date('y/m/');
                    $real_path = Yii::$app->params['upload_path'] . $relative_path;
                    if (!file_exists($real_path)
                        && !FileHelper::createDirectory($real_path)) {
                        throw new Exception('无法创建目录。');
                    }
                    $file_name = substr(uniqid(md5(rand()), true), 0, 10);
                    $file_name .= '-' . Inflector::slug($file->baseName);
                    $file_name .= '.' . $file->extension;
                    $uri = $relative_path . $file_name;
                    if (!$file->saveAs($real_path . $file_name)) {
                        Yii::error('无法保存上传文件：' . print_r($file->error, true));
                        throw new Exception('无法保存文件。');
                    }
                    $publish->value = $uri;
                }
            }
            if ($publish->save()) {
                AgentLog::info($this->agent->id, '保存宣传信息', print_r($publish->attributes, true));
                Yii::$app->session->addFlash('success', '数据已保存。');
                Yii::$app->session->setFlash('redirect', json_encode([
                    'url' => Url::to(['/agent/publish/list']),
                    'txt' => '信息列表'
                ]));
            }
        }
        return $this->render('edit', [
            'publish' => $publish,
        ]);
    }

    /**
     * 设置排序AJAX接口
     * @return array
     */
    public function actionSort()
    {
        $publish = AgentPublish::findOne(['id' => $this->get('id'), 'agent_id' => $this->agent->id]);
        if (empty($publish)) {
            return ['error' => 'NOT_FOUND', 'message' => '没有找到信息。'];
        }
        $sort = $this->get('sort');
        if ($sort > 0) {
            /** @var AgentPublish $sortPublish */
            $sortPublish = AgentPublish::find()
                ->andWhere(['agent_id' => $this->agent->id])
                ->andWhere(['>', 'sort', $publish->sort])
                ->orderBy('sort ASC')
                ->one();
            if (!empty($sortPublish)) {
                $sortPublish->updateCounters(['sort' => -1]);
                $publish->updateCounters(['sort' => 1]);
            }
        } else {/** @var AgentPublish $sortPublish */
            $sortPublish = AgentPublish::find()
                ->andWhere(['agent_id' => $this->agent->id])
                ->andWhere(['<', 'sort', $publish->sort])
                ->orderBy('sort DESC')
                ->one();
            if (!empty($sortPublish)) {
                $sortPublish->updateCounters(['sort' => 1]);
                $publish->updateCounters(['sort' => -1]);
            }
        }
        return [];
    }

    /**
     * 删除信息AJAX接口
     * @return array
     */
    public function actionDelete()
    {
        $publish = AgentPublish::findOne(['id' => $this->get('id'), 'agent_id' => $this->agent->id]);
        if (empty($publish)) {
            return ['error' => 'NOT_FOUND', 'message' => '没有找到信息。'];
        }
        try {
            $publish->delete();
        } catch (\Throwable $_) {
        }
        AgentPublish::updateAllCounters(['sort' => -1], []);
        return [];
    }
}
